package bean;

import java.io.IOException;
import java.util.Calendar;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;

import org.primefaces.event.SelectEvent;

import dao.DoctorDAO;
import dao.JPA;
import dao.TreatmentRequestDAO;
import dao.UserDAO;
import entity.Doctor;
import entity.TreatmentRequest;

@ManagedBean
@ViewScoped
public class ViewDoctorTreatmentRequestListBean {

	@Inject @JPA
	private DoctorDAO doctorDAO;	
	@Inject @JPA
	private UserDAO userDAO;	
	@Inject @JPA
	private TreatmentRequestDAO treatmentRequestDAO;
	private int doctorId;
	private Calendar startDate;
	private Calendar endDate;
	private List<TreatmentRequest> requestList;
	private boolean emptyProfile;
	
	@PostConstruct
	private void init() {		
		int userId = userDAO.selectUserByName(FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal().getName()).getId();		
		Doctor doctor = doctorDAO.selectDoctorByUserId(userId);
		if(doctor == null) {
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "You must fill your profile before viewing requests", "You must fill your profile before viewing requests"));
			emptyProfile = true;
			return;
		}	
		doctorId = doctor.getId();
		startDate = Calendar.getInstance();		
		startDate.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
		startDate.set(Calendar.HOUR_OF_DAY, 0);
		startDate.set(Calendar.MINUTE, 0);
		startDate.set(Calendar.SECOND, 0);
		startDate.set(Calendar.MILLISECOND, 0);		
		endDate = (Calendar) startDate.clone();
		endDate.add(Calendar.DAY_OF_YEAR, 6);	
		requestList = treatmentRequestDAO.selectRequestsByDoctorIdAndDateRange(doctorId, startDate, endDate);		
	}
	
	public void dateChange() {
		if(!emptyProfile)
			requestList = treatmentRequestDAO.selectRequestsByDoctorIdAndDateRange(doctorId, startDate, endDate);		
	}
	
	public void onRowSelect(SelectEvent event) {
		int selectedRequestId = ((TreatmentRequest) event.getObject()).getId();
		try {
			FacesContext.getCurrentInstance().getExternalContext().redirect("viewTreatmentRequest.xhtml?reqId=" + selectedRequestId);
		} catch(IOException ioe) {
			ioe.printStackTrace();
		}
	}

	public Calendar getStartDate() {
		return startDate;
	}

	public void setStartDate(Calendar startDate) {
		this.startDate = startDate;
	}

	public Calendar getEndDate() {
		return endDate;
	}

	public void setEndDate(Calendar endDate) {
		this.endDate = endDate;
	}

	public List<TreatmentRequest> getRequestList() {
		return requestList;
	}
	
}
